<template>
  <div class="app-container" style="padding:1vh 4vw">
    <el-row style="margin: 6vh 2vw;">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
        <el-input v-model="query" style="width: 50%;" class="filter-item" placeholder="输入关键字搜索" @keyup.enter.native="handleFilter" :size="handleSize()"/>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" :size="handleSize()">
          搜索
        </el-button>
        <el-button v-show="device() !== 'mobile'" class="filter-item" style="margin-left: 15px;" type="primary" icon="el-icon-edit" @click="handleCreate" :size="handleSize()">
          添加用户管理员
        </el-button>
        <el-button v-show="device() === 'mobile'" class="filter-item" style="margin-left: 15px;" type="primary" icon="el-icon-edit" @click="handleCreate" :size="handleSize()">
          添加
        </el-button>
        <el-tooltip v-show="device() !== 'mobile'" effect="light" content="即拥有发布活动权限的用户" placement="right" transition="el-zoom-in-center">
          <i class="el-icon-info" style="margin-left: 0.8vw"/>
        </el-tooltip>
      </el-col>
    </el-row>

    <!--    <div class="filter-container">-->
<!--      <el-input v-model="listQuery.key" style="width: 25%;" class="filter-item" placeholder="输入关键字搜索" @keyup.enter.native="handleFilter" />-->
<!--      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">-->
<!--        搜索-->
<!--      </el-button>-->
<!--      <el-tooltip class="item" effect="dark" content="添加可以活动发布的用户" placement="top-start">-->
<!--        <el-button type="primary" style="margin-top: 30px;margin-left: 1.4rem" icon="el-icon-edit" @click="handleCreate">-->
<!--          添加白名单用户-->
<!--        </el-button>-->
<!--      </el-tooltip>-->
<!--    </div>-->

    <div class="table-container" style="margin: 0 2vw;">
      <el-table highlight-current-row fit :data="userAdminsList" style="width: 100%;" max-height="800" :size="handleSize()" tooltip-effect="light">
        <el-table-column fixed sortable prop="id" label="ID" max-width="200" min-width="100" />
<!--        <el-table-column prop="name" label="姓名" max-width="400" min-width="200" align="center" />-->
        <el-table-column label="用户" max-width="400" min-width="200" align="center">
          <template v-slot="scope">
            <el-popover trigger="hover" placement="top">
              <p>姓名: {{ getUserName(scope.row.userId) }}</p>
              <p>学号: {{ getUserNumber(scope.row.userId) }}</p>
              <p>学院: {{ getUserCollege(scope.row.userId) }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ getUserName(scope.row.userId) }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column label="年级" max-width="200" min-width="100">
          <template v-slot="scope">
            {{ getUserGrade(scope.row.userId) }}
          </template>
        </el-table-column>

        <el-table-column prop="major" label="专业" max-width="400" min-width="200" >
          <template v-slot="scope">
            {{ getUserMajor(scope.row.userId) }}
          </template>
        </el-table-column>

        <el-table-column prop="classes" label="班级" max-width="200" min-width="100" >
          <template v-slot="scope">
            {{ getUserClazz(scope.row.userId) }}
          </template>
        </el-table-column>
<!--        <el-table-column sortable prop="number" label="学号" width="150" />-->
<!--        <el-table-column prop="college" label="学院" width="250" />-->
        <el-table-column label="操作" align="center" max-width="400" min-width="200">
          <template v-slot="{row,$index}">
            <el-button size="mini" @click="handleUpdate(row)"  type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
<!--        <el-table-column label="操作">-->
<!--          <template v-slot="{row,$index}">-->
<!--            <el-button size="mini" @click="handleUpdate(row)">编辑</el-button>-->
<!--            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">删除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->

        <el-row style="display: flex;justify-content: center">
          <el-col :xs="18" :sm="12" :md="12" :lg="8" :xl="6" style="display: flex;justify-content: center">
            <el-pagination
              v-show="total>0"
              background
              hide-on-single-page
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-size="perPage"
              layout="prev, pager, next"
              :total="total">
            </el-pagination>
          </el-col>
        </el-row>
      </el-table>

<!--      <el-row type="flex" justify="center" style="margin-top: 30px">-->
<!--        &lt;!&ndash;<el-pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" layout="prev, pager, next" @pagination="getList" />&ndash;&gt;-->
<!--        <el-pagination :page-size="20" :pager-count="11" layout="prev, pager, next" :total="40" />-->
<!--      </el-row>-->

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :fullscreen="device() === 'mobile'">
<!--        :rules="rules"-->
        <el-form ref="dataForm" :model="postForm" :label-position="device() === 'mobile' ? 'top' : 'left'" label-width="70px" style="width: 400px; margin-left:50px;" :size="handleSize()">
          <el-form-item label="用户" prop="user">
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model="postForm.userId"
              :fetch-suggestions="querySearch"
              placeholder="请选择用户"
              @select="handleSelect"
              style="width: 300px">
              <i
                class="el-icon-edit el-input__icon"
                slot="suffix"
                @click="handleIconClick">
              </i>
              <template v-slot="{ item }">
                <div class="title">{{ getUserName(item.userId) }}</div>
                <span class="zone">{{ getUserNumber(item.userId) }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
<!--          <el-form-item label="姓名" prop="name">-->
<!--            <el-input v-model="postForm.name" style="width: 200px" placeholder="请输入姓名" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="学号" prop="number">-->
<!--            <el-input v-model="postForm.number" style="width: 350px" placeholder="请输入学号" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="年级" prop="grade">-->
<!--            <el-select v-model="postForm.grade" class="filter-item" placeholder="请选择年级" style="width: 200px">-->
<!--              <el-option v-for="item in gradeOptions" :key="item.value" :label="item.value" :value="item.value" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="学院" prop="college">-->
<!--            <el-select v-model="postForm.college" class="filter-item" placeholder="请选择学院" style="width:350px;">-->
<!--              <el-option v-for="item in collegeOptions" :key="item.value" :label="item.value" :value="item.value" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="专业" prop="major">-->
<!--            <el-input v-model="postForm.major" style="width: 350px" placeholder="请输入专业" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="班级" prop="classes">-->
<!--            <el-input v-model="postForm.classes" style="width: 200px" placeholder="请输入班级" />-->
<!--          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" @click="dialogFormVisible = false" :size="handleSize()">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()" :size="handleSize()">
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {createArticle, updateArticle} from '@/api/article'
import {changeUserAdmin, indexUserAdmin} from "@/api/admin/userAdmin";
import {isEmpty} from "element-ui";
import {deleteUser} from "@/api/admin/user";

const defaultPostForm = {
  id: undefined,
  userId: undefined
}

// const gradeOptions = [
//   { value: '大一' },
//   { value: '大二' },
//   { value: '大三' },
//   { value: '大四' }
// ]
//
// const collegeOptions = [
//   { value: '管理学院' },
//   { value: '经济学院' },
//   { value: '珠宝学院' },
//   { value: '建筑学院' },
//   { value: '国际商学院' },
//   { value: '外国语学院' },
//   { value: '土木工程学院' },
//   { value: '电气工程学院' },
//   { value: '汽车与交通工程学院' },
//   { value: '计算机工程学院暨大数据学院' },
//   { value: '机械工程学院暨机器人工程学院' },
//   { value: '电子信息学院暨中兴通讯工程学院' }
// ]

export default {
  data() {
    return {
      currentPage: 0,
      lastPage: 0,
      total: 0,
      perPage: 0,
      query: '',
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '创建',
        update: '编辑'
      },
      postForm: Object.assign({}, defaultPostForm),
      rules: {
        user: [{required: true, message: '必选', trigger: 'blur'}]
        // name: [{ required: true, message: '必填', trigger: 'blur' }],
        // number: [{ required: true, message: '必填', trigger: 'blur' }],
        // college: [{ required: true, message: '必填', trigger: 'change' }]
      },
      restaurants: [],
      state: '',
      userAdminsList: [{
        id: 1,
        name: '王小虎',
        number: '202210089001',
        grade: '大一',
        college: '经济学院',
        major: '计算机科学与技术',
        classes: '5班'
      }]
    }
  },
  created() {
    // 从服务器获取 用户管理员列表
    this.getUserAdmins()
  },
  methods: {
    async getUserAdmins() {
      const currentPage = this.currentPage
      const params = new URLSearchParams()
      params.set("currentPage", currentPage)
      const res = indexUserAdmin(params)
      this.userAdminsList = res.data.data
      this.currentPage = res.data.currentPage
      this.lastPage = res.data.lastPage
      this.total = res.data.total
      this.perPage = res.data.perPage
    },
    handleFilter() {
      const query = this.query
      const currentPage = this.currentPage
      const params = new URLSearchParams()
      params.set('query', query)
      params.set("currentPage", currentPage)
      const res = indexUserAdmin(params)
      this.userAdminsList = res.data.data
      this.currentPage = res.data.currentPage
      this.lastPage = res.data.lastPage
      this.total = res.data.total
      this.perPage = res.data.perPage
    },
    device() {
      return this.$store.state.app.device
    },
    handleSize() {
      return this.$store.state.app.device === 'mobile' ? 'mini' : 'medium'
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    resetTemp() {
      this.postForm = {
        id: undefined,
        userid: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      const res = indexUserAdmin(this.postForm.userId)
      if (!isEmpty(res.data.data)) {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            changeUserAdmin(this.postForm).then(() => {
              this.loading = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }else {
            console.log('发布失败!!')
            this.loading = false
            this.$notify({
              title: '失败',
              message: '创建失败',
              type: 'danger',
              duration: 2000
            })
            return false
          }
        })
      }
    },
    handleUpdate(row) {
      this.postForm = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      const res = indexUserAdmin(this.postForm.userId)
      if (!isEmpty(res.data.data)) {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            changeUserAdmin(this.postForm).then(() => {
              this.loading = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            console.log('发布失败!!')
            this.loading = false
            this.$notify({
              title: '失败',
              message: '修改失败',
              type: 'danger',
              duration: 2000
            })
            return false
          }
        });
      } else {
        this.$notify({
          title: '失败',
          message: '找不到该用户',
          type: 'danger',
          duration: 2000
        })
      }
    },
    handleDelete(row, index) {
      console.log(index, row)
      // 权限判断
      if (this.state.user.roles === 'superAdmin') {
        this.$confirm('确定删除此活动', 'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            deleteUserAdmin(row.key)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .catch(err => {
            console.error(err)
          });
      } else {
        this.$notify({
          title: '失败',
          message: '没有权限执行此操作',
          type: 'danger',
          duration: 2000
        })
        // this.$confirm('没有权限执行此操作', 'Warning', {
        //   confirmButtonText: 'Confirm',
        //   type: 'warning'
        // })
      }
      // this.$notify({
      //   title: '成功',
      //   message: '删除成功',
      //   type: 'success',
      //   duration: 2000
      // })
      // this.list.splice(index, 1)
    },
    createData() {
      const res = indexUserAdmin(this.postForm.userId)
      if(!isEmpty(res.data.data)){
        this.$refs['dataForm'].validate((valid) => {
          // if (valid) {
          //   // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          //   createArticle(this.postForm).then(() => {
          //     this.list.unshift(this.postForm)
          //     this.dialogFormVisible = false
          //     this.$notify({
          //       title: '成功',
          //       message: '创建成功',
          //       type: 'success',
          //       duration: 2000
          //     })
          //   })
          // }
          if (valid) {
            this.loading = true
            changeUserAdmin(this.postForm).then(() => {
              this.loading = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            console.log('发布失败!!')
            this.loading = false
            this.$notify({
              title: '失败',
              message: '修改失败',
              type: 'danger',
              duration: 2000
            })
            return false
          }
        })
      } else {
        this.$notify({
          title: '失败',
          message: '找不到该用户',
          type: 'danger',
          duration: 2000
        })
      }
    },
    updateData() {
      const res = indexUserAdmin(this.postForm.userId)
      if (!isEmpty(res.data.data)) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            changeUserAdmin(this.postForm).then(() => {
              this.loading = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            console.log('发布失败!!')
            this.loading = false
            this.$notify({
              title: '失败',
              message: '修改失败',
              type: 'danger',
              duration: 2000
            })
            return false
          }
          // if (valid) {
          //   const tempData = Object.assign({}, this.postForm)
          //   updateArticle(tempData).then(() => {
          //     const index = this.list.findIndex(v => v.id === this.postForm.id)
          //     this.list.splice(index, 1, this.postForm)
          //     this.dialogFormVisible = false
          //     this.$notify({
          //       title: '成功',
          //       message: '修改成功',
          //       type: 'success',
          //       duration: 2000
          //     })
          //   })
          // }
        });
      } else {
        this.$notify({
          title: '失败',
          message: '找不到该用户',
          type: 'danger',
          duration: 2000
        })
      }
    },
    querySearch(queryString, cb) {
      var userId = this.userId;
      var results = queryString ? userId.filter(this.createFilter(queryString)) : userId;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (userId) => {
        return (userId.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadAll() {
      return [
        { "name": "ASTqkxV", "number": "810" },
        { "name": "DMQ1kHqUr", "number": "395" },
        { "name": "ykIjZc8DcI", "number": "907" },
        { "name": "i2T2P84", "number": "566" },
        { "name": "7PWouoxRrcN", "number": "298" },
      ];
    },
    handleSelect(item) {
      console.log(item);
    },
    handleIconClick(ev) {
      console.log(ev);
    },
    getUserName(userId) {
      const query = userId
      const params = new URLSearchParams()
      params.set('query', query)
      const res = indexUserAdmin(params)
      return res.data.data.name
    },
    getUserNumber(userId) {
      const query = userId
      const params = new URLSearchParams()
      params.set('query', query)
      const res = indexUserAdmin(params)
      return res.data.data.number
    },
    getUserMajor(userId) {
      const query = userId
      const params = new URLSearchParams()
      params.set('query', query)
      const res = indexUserAdmin(params)
      return res.data.data.major
    },
    getUserClazz(userId) {
      const query = userId
      const params = new URLSearchParams()
      params.set('query', query)
      const res = indexUserAdmin(params)
      return res.data.data.clazz
    },
    getUserCollege(number) {
      const query = number
      const params = new URLSearchParams()
      params.set('query', query)
      const res = indexUserAdmin(params)
      return res.data.data.college
    },
    getUserGrade(number) {
      const query = number
      const params = new URLSearchParams()
      params.set('query', query)
      const res = indexUserAdmin(params)
      return res.data.data.grade
    }
  },
  mounted() {
    this.restaurants = this.loadAll();
  }
}
</script>

<style scoped lang="scss">
.app-container {
  //margin: 30px 2rem;
  //border-radius: 15px;
  //box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);

  //.filter-container {
  //  margin-right: 30px;
  //  margin-left: 30px;
  //  margin-top: 30px;
  //}
}

.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .title {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .zone {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .zone {
      color: #ddd;
    }
  }
}
</style>

<!--, {-->
<!--id: 2,-->
<!--name: '王小虎',-->
<!--number: '202210089002',-->
<!--grade: '大二',-->
<!--college: '管理学院',-->
<!--major: '计算机科学与技术',-->
<!--classes: '4班'-->
<!--}, {-->
<!--id: 3,-->
<!--name: '王小虎',-->
<!--number: '202210089003',-->
<!--grade: '大三',-->
<!--college: '计算机工程学院暨大数据学院',-->
<!--major: '计算机科学与技术',-->
<!--classes: '3班'-->
<!--}, {-->
<!--id: 4,-->
<!--name: '王小虎',-->
<!--number: '202210089004',-->
<!--grade: '大四',-->
<!--college: '电气工程学院',-->
<!--major: '大数据',-->
<!--classes: '2班'-->
<!--}, {-->
<!--id: 5,-->
<!--name: '王小虎',-->
<!--number: '202210089005',-->
<!--grade: '大一',-->
<!--college: '电子信息学院暨中兴通讯工程学院',-->
<!--major: '大数据',-->
<!--classes: '1班'-->
<!--}-->

<!--{ "value": "贡茶", "address": "上海市长宁区金钟路633号" },-->
<!--{ "value": "豪大大香鸡排超级奶爸", "address": "上海市嘉定区曹安公路曹安路1685号" },-->
<!--{ "value": "茶芝兰（奶茶，手抓饼）", "address": "上海市普陀区同普路1435号" },-->
<!--{ "value": "十二泷町", "address": "上海市北翟路1444弄81号B幢-107" },-->
<!--{ "value": "星移浓缩咖啡", "address": "上海市嘉定区新郁路817号" },-->
<!--{ "value": "阿姨奶茶/豪大大", "address": "嘉定区曹安路1611号" },-->
<!--{ "value": "新麦甜四季甜品炸鸡", "address": "嘉定区曹安公路2383弄55号" },-->
<!--{ "value": "Monica摩托主题咖啡店", "address": "嘉定区江桥镇曹安公路2409号1F，2383弄62号1F" },-->
<!--{ "value": "浮生若茶（凌空soho店）", "address": "上海长宁区金钟路968号9号楼地下一层" },-->
<!--{ "value": "NONO JUICE  鲜榨果汁", "address": "上海市长宁区天山西路119号" },-->
<!--{ "value": "CoCo都可(北新泾店）", "address": "上海市长宁区仙霞西路" },-->
<!--{ "value": "快乐柠檬（神州智慧店）", "address": "上海市长宁区天山西路567号1层R117号店铺" },-->
<!--{ "value": "Merci Paul cafe", "address": "上海市普陀区光复西路丹巴路28弄6号楼819" },-->
<!--{ "value": "猫山王（西郊百联店）", "address": "上海市长宁区仙霞西路88号第一层G05-F01-1-306" },-->
<!--{ "value": "枪会山", "address": "上海市普陀区棕榈路" },-->
<!--{ "value": "纵食", "address": "元丰天山花园(东门) 双流路267号" },-->
<!--{ "value": "钱记", "address": "上海市长宁区天山西路" },-->
<!--{ "value": "壹杯加", "address": "上海市长宁区通协路" },-->
<!--{ "value": "唦哇嘀咖", "address": "上海市长宁区新泾镇金钟路999号2幢（B幢）第01层第1-02A单元" },-->
<!--{ "value": "爱茜茜里(西郊百联)", "address": "长宁区仙霞西路88号1305室" },-->
<!--{ "value": "爱茜茜里(近铁广场)", "address": "上海市普陀区真北路818号近铁城市广场北区地下二楼N-B2-O2-C商铺" },-->
<!--{ "value": "鲜果榨汁（金沙江路和美广店）", "address": "普陀区金沙江路2239号金沙和美广场B1-10-6" },-->
<!--{ "value": "开心丽果（缤谷店）", "address": "上海市长宁区威宁路天山路341号" },-->
<!--{ "value": "超级鸡车（丰庄路店）", "address": "上海市嘉定区丰庄路240号" },-->
<!--{ "value": "妙生活果园（北新泾店）", "address": "长宁区新渔路144号" },-->
<!--{ "value": "香宜度麻辣香锅", "address": "长宁区淞虹路148号" },-->
<!--{ "value": "凡仔汉堡（老真北路店）", "address": "上海市普陀区老真北路160号" },-->
<!--{ "value": "港式小铺", "address": "上海市长宁区金钟路968号15楼15-105室" },-->
<!--{ "value": "蜀香源麻辣香锅（剑河路店）", "address": "剑河路443-1" },-->
<!--{ "value": "北京饺子馆", "address": "长宁区北新泾街道天山西路490-1号" },-->
<!--{ "value": "饭典*新简餐（凌空SOHO店）", "address": "上海市长宁区金钟路968号9号楼地下一层9-83室" },-->
<!--{ "value": "焦耳·川式快餐（金钟路店）", "address": "上海市金钟路633号地下一层甲部" },-->
<!--{ "value": "动力鸡车", "address": "长宁区仙霞西路299弄3号101B" },-->
<!--{ "value": "浏阳蒸菜", "address": "天山西路430号" },-->
<!--{ "value": "四海游龙（天山西路店）", "address": "上海市长宁区天山西路" },-->
<!--{ "value": "樱花食堂（凌空店）", "address": "上海市长宁区金钟路968号15楼15-105室" },-->
<!--{ "value": "壹分米客家传统调制米粉(天山店)", "address": "天山西路428号" },-->
<!--{ "value": "福荣祥烧腊（平溪路店）", "address": "上海市长宁区协和路福泉路255弄57-73号" },-->
<!--{ "value": "速记黄焖鸡米饭", "address": "上海市长宁区北新泾街道金钟路180号1层01号摊位" },-->
<!--{ "value": "红辣椒麻辣烫", "address": "上海市长宁区天山西路492号" },-->
<!--{ "value": "(小杨生煎)西郊百联餐厅", "address": "长宁区仙霞西路88号百联2楼" },-->
<!--{ "value": "阳阳麻辣烫", "address": "天山西路389号" },-->
<!--{ "value": "南拳妈妈龙虾盖浇饭", "address": "普陀区金沙江路1699号鑫乐惠美食广场A13" }-->
